<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="6" :xs="24">
        <!-- <div class="head-container">
          <el-input v-model="categoryName" placeholder="请输入分类名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px"/>
        </div>
        <div class="head-container">
          <el-tree :data="cateOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode"
                   ref="tree" default-expand-all highlight-current @node-click="handleNodeClick"/>
        </div>-->
        <el-table :data="activeData" v-loading="loading" style="width: 100%">
          <el-table-column prop="subjectName" label="题目名称" width="220">
            <template slot-scope="scope">{{resHtml(scope.row.subjectName)}}</template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="deleteRow(scope.$index, activeData)"
                type="text"
                size="small"
                v-hasPermi="['exam:examination-subject:delete']"
              >移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" class="checkBtn" icon="el-icon-check" @click="checkBtn">完成</el-button>
        <div class="txt">增加了{{activeData.length}}道题目</div>
      </el-col>
      <el-col :span="18" :xs="24">
        <!-- 搜索工作栏 -->
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="归属分类" prop="categoryId">
            <treeselect
              v-model="queryParams.categoryId"
              :options="cateOptions"
              :show-count="true"
              :clearable="false"
              placeholder="请选择归属分类"
              :normalizer="normalizer"
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="题目类型" prop="choicesType">
            <el-select v-model="queryParams.choicesType" placeholder="请选择题目类型">
              <el-option
                v-for="dict in this.getDictDatas(DICT_TYPE.CHOICES_TYPE)"
                :key="dict.value"
                :value="parseInt(dict.value)"
                :label="dict.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="题目名称" prop="subjectName">
            <el-input
              v-model="queryParams.subjectName"
              placeholder="请输入题目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-plus" @click="addBtn">新增</el-button>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 操作工具栏 -->
        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                      v-hasPermi="['exam:subject-short-answer:create']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                      v-hasPermi="['exam:subject-short-answer:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>-->
        <!-- 列表 -->
        <el-table v-loading="loading" :data="list">
          <el-table-column
            label="题目名称"
            align="center"
            prop="subjectName"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">{{resHtml(scope.row.subjectName)}}</template>
          </el-table-column>
          <el-table-column label="分值" align="center" prop="score" width="50"/>
          <el-table-column label="题目类型" align="center" prop="choicesType">
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.CHOICES_TYPE" :value="scope.row.choicesType"/>
            </template>
          </el-table-column>
          <el-table-column label="难度等级" align="center" prop="level">
            <template slot-scope="scope">
              <el-rate :value="scope.row.level" disabled></el-rate>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="150">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label=" " align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-circle-check"
                @click="addSubject(scope.row)"
                v-hasPermi="['exam:examination-subject:create']"
                :disabled="disableds"
              >选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNo"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  deleteSubjectChoices,
  getSubjectChoicesPage,
  exportSubjectChoicesExcel
} from "@/api/exam/subjectChoices";
import {
  createExaminationSubject,
  getExaminationSubjectList,
  deleteExaminationSubject
} from "@/api/exam/examination";
import { getSimpleList } from "@/api/examination/subjectCategory";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Subject",
  components: {
    Treeselect
  },
  data() {
    return {
      //
      isTrue: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 列表
      list: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        subjectName: null
      },
      // 表单参数
      form: {},
      activeData: [],
      defaultProps: {
        children: "children",
        label: "categoryName"
      },
      cateOptions: [],
      categoryName: undefined,
      //默认标签页
      activeName: 0,
      // 题目临时信息

      // 选中状态
      status: 0,
      disableds: false
    };
  },
  watch: {
    // 根据名称筛选分类
    categoryName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getSubjectList();
  },
  methods: {
    //移除
    deleteRow(index, rows) {
      deleteExaminationSubject(rows[index].id).then(() => {
        rows.splice(index, 1);
        this.getList();
        this.$modal.msgSuccess("删除成功");
      });
      return;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getSubjectChoicesPage(this.queryParams).then(response => {
        this.list = response.data.list;
        console.log(this.list);

        this.total = parseInt(response.data.total);
        this.loading = false;
      });
    },
    getSubjectList() {
      this.loading = true;
      // 执行查询
      const Id = this.$route.params.id;
      getExaminationSubjectList(Id).then(response => {
        this.activeData = response.data;
        console.log(this.activeData);

        this.loading = false;
      });
    },
    /** 查询分类下拉树结构 */
    getTreeselect() {
      getSimpleList().then(response => {
        // 处理 deptOptions 参数
        this.cateOptions.push(...this.handleTree(response.data, "id"));
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.categoryName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.categoryId = data.id;
      this.getList();
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      (this.tempSubject = {}), this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 添加题目按钮操作 */
    addSubject(row) {
      console.log(row);
      this.loading = true;
      if (row.id != null && row.id > 0) {
        const addForm = {
          categoryId: row.categoryId,
          examinationId: this.$route.params.id,
          subjectId: row.id,
          type: row.choicesType
        };
        createExaminationSubject(addForm)
          .then(res => {
            console.log(res);

            if (res.data == null) {
              this.$modal.msgError(res.msg);
            } else {
              this.$modal.msgSuccess("新增成功");
            }

            this.loading = false;
            this.getList();
            this.getSubjectList();
          })
          .catch(res => {
            //this.$modal.msgError('题目已存在');
            this.loading = false;
          });
      } else {
        this.$modal.msgError("该试题不存在");
        this.loading = false;
      }
    },
    /** 提交按钮 */
    // submitForm() {
    //   const ref = this.getSubjectRef()
    //   if(ref.validate()) {
    //     let subjectInfo = ref.getSubjectInfo()
    //     // 修改的提交

    //     if (subjectInfo.id != null && subjectInfo.id>0) {
    //       updateSubjectChoices(subjectInfo).then(response => {
    //         this.$modal.msgSuccess("修改成功");
    //         this.open = false;
    //         this.getList();
    //       });
    //       return;
    //     }
    //     // 添加的提交
    //     createSubjectChoices(subjectInfo).then(response => {
    //       this.$modal.msgSuccess("新增成功");
    //       this.open = false;
    //       this.getList();
    //     });
    //   }
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除选择题编号为"' + id + '"的数据项?')
        .then(function() {
          return deleteSubjectChoices(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal
        .confirm("是否确认导出所有选择题数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportSubjectChoicesExcel(params);
        })
        .then(response => {
          this.$download.excel(response, "选择题.xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    // 格式化课程树的下拉框
    normalizer(node) {
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
    resHtml(item) {
      return item.replace(/<[^>]+>/g, ""); // 去掉所有的html标记
    },
    checkBtn() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push("/exam/examination");
    },
    addBtn() {
      this.$router.replace("/exam/exam/subject-choices");
    }
  }
};
</script>
<style lang="scss" scoped>
.checkBtn {
  position: relative;
  top: 30px;
  width: 100%;
}
.txt {
  width: 100%;
  height: 100px;
  margin-top: 40px;
  font-size: 15px;
  color: #cccccc;
  text-align: center;
}
</style>
